''' renderer.py
INPUT: 
types - A list of the types of data to be displayed
sample_types = ['hostname', 'status','uptime','disk_space']

data - A list of dictionaries
sample_data = {'planetlab.venus.jp': {'status': 'up', 'uptime':'318', 'disk_space':'1354/3621'}, 
               'planetlab.earth.ca': {'status': 'up', 'uptime':'8479', 'disk_space':'238822/168791'}}

Creates a html file that contains a sortable table of the data from the input'''

import sys

sample_data = {'planetlab.venus.jp': {'status': 'up', 'uptime':'318', 'disk_space':'1354/3621'}, 
               'planetlab.earth.ca': {'status': 'up', 'disk_space':'238822/168791'}}

HEADER = """
<html>
    <head>
    <script type="text/javascript" src="sorttable.js"></script>
    <title>Sortable(!) Planetlab Nodes Table</title>
    </head>
    
    <body>
    <center>
    <table class="sortable" border="1" bordercolor=#FFFFFF bgcolor=#A9D0F5 style="border-collapse:collapse;font-size:13px">
        <thead>
        <tr>
            <th>Hostname</th>
"""
MIDDLE =  """
        </tr>
        </thead>
        
        <tbody>
"""
FOOTER = """
        </tbody>
    </table>
    </center>
    </body>
</html>
"""

def render(data):
        
        try:
		hostnames = data.keys()
		datatypes = data[hostnames[0]].keys()
		for host in hostnames:
			if len(data[host]) > len(datatypes):
				datatypes = data[host].keys()
		f = open('monitor.html','w')
		f.write(HEADER)
		for item in datatypes:
			f.write("            <th align=center>"+item+"</th>\n")
		f.write(MIDDLE)
		for host in hostnames:
			f.write("        <tr>\n")
			f.write("        <td align=center>"+host+"</td>")
			for item in datatypes:
				if item in data[host]:
					f.write("            <td align=center>"+str(data[host][item])+"</td>\n")
				else:
					f.write("<td></td>")
			f.write("        </tr>\n")
		f.write(FOOTER)
		f.close()
	except IOError, e:
		print >>sys.stderr, "Failed to open file: %d (%s)" % (e.errno, e.strerror)
